package com.assignwork.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音工具
 *
 * @author ：dujianyu
 * @since ：Created in 2022/6/14 15:43
 */
public class PinyinUtil {
    public static String getPinyin(String china){
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        StringBuilder result = new StringBuilder();
        try {
            for (char ti : arrays) {
                /*
                 *  匹配是否是中文
                 * */
                if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, format);
                    result.append(temp[0]);
                } else {
                    result.append(ti);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

        return result.toString();
    }

    public static String getPinYinHeaderChar(String str){
        StringBuilder convert= new StringBuilder();
        for (   int i =   0 ; i < str.length(); i++ ) {
            char word=str.charAt(i);
            String[] pinYinArray=PinyinHelper.toHanyuPinyinStringArray(word);
            if ( pinYinArray!=  null ){
                convert.append(pinYinArray[0].charAt(0));
            }  else {
                convert.append(word);
            }
        }
        return convert.toString().toLowerCase();
    }
}
